package MediaOnline.WebService;

import java.io.IOException;
import java.util.ArrayList;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import MediaOnline.Adapter.VideoAdapter;
import MediaOnline.Adapter.VideoAdapter2;
import MediaOnline.Data.videoData;
import MediaOnline.GUI.actFilmMain3;
import MediaOnline.GUI.actListFilm;
import MediaOnline.General.paramConst;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;

public class getVideoByPage extends AsyncTask<String, Void, String> {
		//Khai bao thong tin can thiet de goi web service
		public Context mcontext=null;
		private static final String Soap_MethodName = "AndroidGetFilmByPage_Chapter";
		private static final String Soap_Action = paramConst.Webservice_NameSpace+Soap_MethodName;
		private static final String Soap_NameSpace = paramConst.Webservice_NameSpace;
		private static final String Soap_URL = paramConst.Webservice_Url+"filmservice.asmx?op="+Soap_MethodName;
		final SoapObject request = new SoapObject(Soap_NameSpace, Soap_MethodName);

	  	ArrayList<String> arrFilmNameChinh = new ArrayList<String>();
	  	ArrayList<String> arrFilmNamePhu = new ArrayList<String>();
	  	ArrayList<String> arrFilmID = new ArrayList<String>();
	  	ArrayList<String> arrCat = new ArrayList<String>();
	  	ArrayList<String> arrLink = new ArrayList<String>();
	  	ArrayList<String> arrThumbUrl = new ArrayList<String>();
	  	ArrayList<String> arrMoTa = new ArrayList<String>();
	  	ArrayList<String> arrGia = new ArrayList<String>();
	  	ArrayList<Integer> arrDanhGia = new ArrayList<Integer>();
	  	ArrayList<Integer> arrSoTap = new ArrayList<Integer>();
	  	ArrayList<Drawable> arrThumb = new ArrayList<Drawable>();
	  	public int start=0;
	  	final int length=paramConst.SoPhanTuTrongTrang;
	  	public static int filmCatID=-1;
	  	public static String sapxep="F.CreateDate DESC";
	  	public static String timkiem="";
	  	public static int BoLe = 1;		//0: bộ, -1: lẻ,
	  	public static String where="";
		boolean complete=false;
		VideoAdapter adpListVideo;
		//Dialog the hien tien trinh
		ProgressDialog progress; 
		Context ctx;
		public getVideoByPage(Context ctx) {
			arrFilmNameChinh = new ArrayList<String>();
			arrFilmID = new ArrayList<String>();
		  	arrLink = new ArrayList<String>();
		  	arrThumb = new ArrayList<Drawable>();
		  	arrSoTap = new ArrayList<Integer>();
		  	arrThumbUrl = new ArrayList<String>();
	        this.ctx = ctx;
	        progress = new ProgressDialog(ctx);
	        //Lấy vị trí bắt đầu theo trang
	        start = (actFilmMain3.Trang-1)*length+1;
	        Log.d("Start:::::", ""+start);
	        Log.d("Soap URL:::::", Soap_URL);
	        
	    }
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			Log.d("note::::::", "asynctask.post");
			progress.dismiss();
			complete=true;
			//===== 
			//Cap nhat den class video data
			videoData.lstVideoID = arrFilmID;
			videoData.lstVideo = arrFilmNameChinh;
			videoData.lstDanhGia = arrDanhGia;
			videoData.lstMoTa = arrMoTa;
			videoData.lstVideoTenPhimPhu = arrFilmNamePhu;
			videoData.lstGia = arrGia;
			
			videoData.lstVideoLink=arrLink;
			VideoAdapter.arrListFilm=arrFilmNameChinh;
			VideoAdapter2.arrListFilm=arrFilmNameChinh;
			
			videoData.lstFilmCat=arrCat;
			videoData.lstThumbUrl=arrThumbUrl;
			videoData.lstThumb=arrThumb;
			videoData.lstSoTap=arrSoTap;
			Log.d("note::::::", "so dong du lieu : "+videoData.lstVideo.size());
			actFilmMain3.lblTongSoTrang.setText(" /"+actFilmMain3.TongSoTrang);
			//Load danh sach phim
			actListFilm.ViewList();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			//Reset arraylist
			arrFilmNameChinh = new ArrayList<String>();
			arrLink= new ArrayList<String>();;
			arrThumb= new ArrayList<Drawable>();
			arrFilmID = new ArrayList<String>();
			arrThumbUrl = new ArrayList<String>();
			//Chay progress dialog
			progress.setMessage("Đang tải dữ liệu phim. Vui lòng đợi!!!");
			progress.setIndeterminate(true);
			progress.setCancelable(false);
			progress.show();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			final SoapSerializationEnvelope Soap_Evelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
	        Soap_Evelope.dotNet=true;
	        final HttpTransportSE androidHttpTransport = new HttpTransportSE(Soap_URL);
	        //Gui cau lenh truy van
	        request.addProperty("startIndex",start);
			request.addProperty("length",length);
			//Nếu có lệnh sắp xếp thì sẽ sắp xếp
			if (!sapxep.equals("")) {
				request.addProperty("Orderby",sapxep);
			}
			if (!timkiem.equals("")) {
				where = "(F.FilmName like '%"+timkiem+"%' OR F.Alias like '%"+timkiem+"%' OR F.FilmNameOriginal like '%"+timkiem+"%') AND F.Parent<=0";
			}
			else{
				//Lúc mới vào chương trình chưa chọn gì hết
				if (filmCatID==-1 && BoLe==1) {
					where = "F.Parent<=0";
				}
				//Nếu có chọn
				else{
						//Neu ko co film cat thi lay danh sach moi nhat
						Log.d("FilmcatID=======", ""+filmCatID);
						if(filmCatID!=-1){
							where = "FC.CategoryID="+filmCatID;
						}
						//Neu co phim cat ID thi lay danh sach phim theo phimcat 
						else{
							
						}
					//Nếu có chọn phim bộ hay phim lẽ thì add thêm câu lệnh
					if (BoLe==0 || BoLe==-1) {	//Nếu là phim bộ hoặc phim lẻ
						if (filmCatID!=-1) {
							where +=" AND F.Parent="+BoLe;
						}
						else {
							where ="F.Parent="+BoLe;
						}
						
					}
					else {	//Nếu là tất cả
						if (filmCatID!=-1) {
							where +=" AND F.Parent<=0";
						}
						else {
							where ="F.Parent<=0";
						}
						
					}
				}
			}
			
			
			request.addProperty("Where", where );
			for (int i = 0; i < request.getPropertyCount(); i++) {
				Log.d("Property::::::", request.getProperty(i).toString());
			}
			Soap_Evelope.setOutputSoapObject(request);
			try{
				for (int i = 0; i < request.getPropertyCount(); i++) {
					Log.d("Property:::::::-------:::::::", request.getProperty(i).toString());
				}
				androidHttpTransport.call(Soap_Action, Soap_Evelope);
				SoapObject respond = (SoapObject) Soap_Evelope.bodyIn;
				respond = (SoapObject) Soap_Evelope.getResponse();
				//loc cac thong tin thua
				respond = (SoapObject) respond.getProperty(0);
				//Lấy tổng số phim
				actFilmMain3.TongSoTrang = Integer.parseInt(respond.getAttributeAsString("Count").toString());
				Log.d("Tong so phim:::::", ""+actFilmMain3.TongSoTrang);
				if (actFilmMain3.TongSoTrang%length==0) {
					actFilmMain3.TongSoTrang = actFilmMain3.TongSoTrang/length;
					if (actFilmMain3.TongSoTrang==0) {
						actFilmMain3.TongSoTrang=1;
					}
					
				}
				else{
					actFilmMain3.TongSoTrang = actFilmMain3.TongSoTrang/length +1;
				}
				Log.d("Tong so trang::::::", ""+actFilmMain3.TongSoTrang);
				//Key mã hóa
            	videoData.MAIN_KEY=respond.getAttribute("KEY").toString();
            	Log.d("Key::::", respond.getAttribute("KEY").toString());
	            //Lay so dong du lieu da nhan ve
	            int x = respond.getPropertyCount();
	            if(x==0){
	            }
	            else{
	            	//Neu du lieu nhan ve >0 dong
	            	//==================Lay thong tin can thiet====================
		            for (int y=0;y<x;y++){
		            	SoapObject respond2 = (SoapObject) respond.getProperty(y);
		            	Log.d("Attribute count:::::", ""+respond2.getAttributeCount());
		            	Log.d("respond:::::::::", respond2.toString());
		            	String s="";
		            	//Lay thông tin phim
		            	//Film ID
		            	arrFilmID.add(respond2.getProperty("FilmID").toString());  	
		            	//Film name
		            	s=respond2.getProperty("FilmName").toString();				
		            	arrFilmNameChinh.add(s);
		            	//Tên phim phụ
		            	arrFilmNamePhu.add(respond2.getProperty("FilmNameOriginal").toString());	
		            	//Số tập của phim bộ
		            	int tap = Integer.parseInt(respond2.getAttribute(0).toString());
		            	arrSoTap.add(tap);		
		            	//Link phim
		            	String link="";
		            	link=respond2.getProperty("Url").toString();		
		            	arrLink.add(link);		            	
		            	//Mô tả
		            	arrMoTa.add(respond2.getProperty("Desciption").toString());
		            	//Đánh giá
		            	arrDanhGia.add(Integer.parseInt(respond2.getProperty("RatingSum").toString()));
		            	//Giá
		            	arrGia.add(respond2.getProperty("Price").toString());
		            	//Thumbail url
		            	String thumb_url = paramConst.URL_ROOT+respond2.getProperty("ThumbImage").toString();
		            	arrThumbUrl.add(thumb_url);
		            	arrThumb.add(null);

		            }
		            //=============================================================
	            }
				
			} catch (IOException e) {
				
			}
			 catch (XmlPullParserException e) {
				
			} catch (ClassCastException e) {
				
			}
			return null;
	}
		
		
		
}
